package com.itwlj.service.impl;

import com.itwlj.constant.MessageConstant;
import com.itwlj.dto.CategoryDTO;
import com.itwlj.entity.Category;
import com.itwlj.exception.DeletionNotAllowedException;
import com.itwlj.mapper.CategoryMapper;
import com.itwlj.mapper.SubCategoryMapper;
import com.itwlj.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 分类业务层
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private SubCategoryMapper subCategoryMapper;

    /**
     * 新增分类
     *
     * @param categoryDTO
     */
    @CacheEvict(value = "category", allEntries = true)
    public void insert(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        categoryMapper.insert(category);
    }

    /**
     * 查询分类
     *
     * @return
     */
    @Cacheable(value = "category", key = "'list'")
    public List<Category> list() {
        List<Category> categoryList = categoryMapper.list();
        return categoryList;
    }

    /**
     * 根据id删除分类
     *
     * @param id
     */
    @CacheEvict(value = "category", allEntries = true)
    public void deleteById(Long id) {
        Integer count = subCategoryMapper.countByCategoryId(id);
        if (count > 0) {
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SUBCATEGORY);
        }

        categoryMapper.deleteById(id);
    }

    /**
     * 根据id修改分类
     *
     * @param categoryDTO
     */
    @CacheEvict(value = "category", allEntries = true)
    public void update(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        categoryMapper.update(category);
    }

    /**
     * 根据id查询分类
     *
     * @param id
     * @return
     */
    @Cacheable(value = "category", key = "#id")
    public Category getById(Long id) {
        Category category = categoryMapper.getById(id);
        return category;
    }
}
